import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { getInfo } from "@/api/user";
import { logoutApi } from "@/api/login";

export const useUserStore = defineStore("user", () => {
  const userInfo = ref();

  const setUserInfo = () => {
    getInfo().then((res) => {
      if (res.code === 200) {
        userInfo.value = res.data;
      }
    });
  };

  const hasPermission = (permissions: string[] | undefined) => {
    if (!userInfo.value || !permissions) {
      return true;
    }

    // 如果是超级管理员，则返回true
    if (userInfo.value.isSuper) {
      return true;
    }
    return permissions.some((permission) =>
      userInfo.value.permissions?.includes(permission),
    );
  };

  const isSuper = computed(() => userInfo.value?.is_super || false);

  const logout = () => {
    logoutApi();
    userInfo.value = null;
  };

  return {
    userInfo,
    isSuper,
    hasPermission,
    logout,
    setUserInfo,
  };
});
